'use strict';

angular.module('hanxinBroker', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngResource', 'ui.router', 'ui.bootstrap', 'ionic', 'ngDialog', 'angular-growl'])
  .config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
      .state('login', {
        url: '/login',
        templateUrl: 'app/login/login.html',
        controller: 'LoginCtrl as vm'
      })
      .state('subscribe', {
        url: '/subscribe',
        template: '<ion-nav-view></ion-nav-view>'
      })
      .state('subscribe.home', {
        url: '/home',
        templateUrl: 'app/subscribe/subscribe.html',
        controller: 'SubscribeCtrl as vm'
      })
      .state('subscribe.list', {
        url: '/list',
        templateUrl: 'app/subscribe/list/list.html',
        controller: 'SubscribeListCtrl as vm'
      })
      .state('modifyPwd', {
        url: '/modifyPwd',
        templateUrl: 'app/modifyPwd/modifyPwd.html',
        controller: 'ModifyPwdCtrl as vm'
      })
      .state('userHome', {
        url: '/userHome',
        templateUrl: 'app/userHome/userHome.html',
        controller: 'UserHomeCtrl as vm'
      })
      .state('myInvitationCode', {
        url: '/myInvitationCode',
        templateUrl: 'app/myInvitationCode/myInvitationCode.html',
        controller: 'MyInvitationCodeCtrl as vm'
      });

    $urlRouterProvider.otherwise('/subscribe/home');
  });


angular.module('hanxinBroker').run(function ($rootScope, Auth, $state, $location, AuthedTransitionService) {
  $rootScope.$on('$locationChangeStart', function (event, next) {
    AuthedTransitionService.setState(next);
    console.log(next);

    jQuery.ajax({
      url: 'broker/api/brokers/currentBroker',
      dataType: "json",
      contentType: "application/json;charset=utf-8",
      async: false,
      statusCode: {
        401: function () {
          $location.path('/login');
        },
        400: function () {
          $location.path('/login');
        }
      },
      success: function (currentUser) {
        if (currentUser.isFirstLogin === "Y") {
          $location.path('/modifyPwd');
        }
      }
    });

  });
});

